import 'package:flutter/material.dart';
import 'package:hxdj/common/base_page/my_loading_page.dart';
import 'package:hxdj/common/components/my_clip_rect.dart';
import 'package:hxdj/common/components/my_scrollView.dart';
import 'package:hxdj/common/components/my_tap_widget.dart';
import 'package:hxdj/common/components/my_text.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:hxdj/common/routers/navigator.dart';
import 'package:hxdj/common/utils/my_date_util.dart';
import 'package:hxdj/home/order/order_detail/order_count_down.dart';
import 'package:hxdj/home/order/order_detail/order_detail_viewmodel.dart';
import 'package:hxdj/home/order/order_manager.dart';
import 'package:hxdj/home/order/order_model.dart';
import 'package:hxdj/home/project_details/project_details_page.dart';

//账号安全
class OrderDetailPage extends StatefulWidget {
  final String orderId;

  static String routeName = "/OrderDetailPage";

  const OrderDetailPage({super.key, required this.orderId});

  @override
  State<OrderDetailPage> createState() => _OrderDetailPageState();
}

class _OrderDetailPageState extends State<OrderDetailPage> {
  //viewModel
  late OrderDetailViewModel viewModel;

  @override
  void initState() {
    super.initState();
  }

  _buildBody() {
    switch (viewModel.state) {
      case ViewState.loading:
        return const MyLoadingWidget();
      default:
        return MyScrollView(
          crossAxisAlignment: CrossAxisAlignment.start,
          bottomButton: _buildOperationArea(),
          children: [
            //订单状态
            _buildOrderStatue(),

            //订单套餐
            _buildOrderPackage(),

            //订单详情
            _buildOrderDetail(),
          ],
        );
    }
  }

  //订单状态
  Widget _buildOrderStatue() {
    OrderModel orderModel = viewModel.orderModel;
    //倒计时支付
    if (viewModel.orderModel.orderStatus == 1) {
      //待支付
//    1. 未支付，超时未支付的倒计时：
// order_duration   =》 按摩订单超时未支付，自动删除订单倒计时
// service_time =》 服务器当前时间
// create_time =》 下单时间
// 剩余时间（秒） ： order_duration - （service_time - create_time）
      int createTime = MyDateUtil.dateToTimestamp(orderModel.createTime!) ~/ 1000;
      int orderDuration = int.parse(orderModel.orderDuration!);
      int surplusTime = orderDuration - (orderModel.serviceTime! - createTime);
      return Container(
          alignment: Alignment.center,
          color: MyColours.colorFF4414.withOpacity(0.4),
          padding: EdgeInsets.only(top: 16.w, bottom: 16.w, left: 20.w),
          child: OrderCountDown(
              remainingTime: surplusTime,
              callback: () {
                //一结束的回调, 去刷新当前的订单详情
                debugPrint("已结束");
                //刷新订单详情
              }));
    } else {
      return Container();
    }

    // return Container(
    //   alignment: Alignment.centerLeft,
    //   color: MyColours.appMain.withOpacity(0.4),
    //   padding: EdgeInsets.only(top: 16.w, bottom: 16.w, left: 20.w),
    //   child: MyText("交易关闭", color: MyColours.appMain, fontSize: 13.sp),
    // );
  }

  //订单套餐
  Widget _buildOrderPackage() {
    return Container(
        decoration: BoxDecoration(
          color: MyColours.materialBg,
          //设置四周圆角 角度
          borderRadius: BorderRadius.circular(17.w),
        ),
        margin: EdgeInsets.only(top: 15.w, bottom: 15.w, left: 10.w, right: 10.w),
        padding: EdgeInsets.only(top: 10.w, bottom: 15.w, left: 10.w, right: 10.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
                child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                MyClipRect(imageUrl: viewModel.orderModel.mImg ?? "", width: 60.w, height: 60.w, radius: 5.w),
                Expanded(
                  child: Container(
                    padding: EdgeInsets.only(left: 8.5.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                          padding: EdgeInsets.only(top: 6.w, bottom: 10.w),
                          child: MyText(viewModel.orderModel.goodsTitle ?? "", textStyle: MyTextStyles.textBlack14),
                        ),
                        MyText(viewModel.orderModel.goodsServiceDuration ?? "",
                            color: MyColours.textGray, fontSize: 11.sp),
                      ],
                    ),
                  ),
                ),
                Container(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Padding(
                        padding: EdgeInsets.only(top: 15.w, bottom: 15.w),
                        child:
                            MyText("¥${viewModel.orderModel.goodsPrice ?? ""}", color: MyColours.text, fontSize: 15.sp),
                      ),
                      MyText("x${viewModel.orderModel.payNum}", color: MyColours.textGray, fontSize: 12.sp),
                    ],
                  ),
                ),
              ],
            )),
            Container(
                padding: EdgeInsets.only(top: 6.5.w, bottom: 6.5.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    MyText("套餐总价", textStyle: MyTextStyles.textBlack12),
                    MyText("¥${viewModel.orderModel.goodsPrice}", textStyle: MyTextStyles.textBlack12),
                  ],
                )),
            Container(
                padding: EdgeInsets.only(top: 6.5.w, bottom: 6.5.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    MyText("技师出行费（地铁+出租车）", textStyle: MyTextStyles.textBlack12),
                    MyText("${viewModel.orderModel.commutePrice}", textStyle: MyTextStyles.textBlack12),
                  ],
                )),
            Container(
              alignment: Alignment.centerRight,
              padding: EdgeInsets.only(top: 6.5.w, bottom: 5.w),
              child: MyText("合计付款 ${viewModel.orderModel.orderPrice}", textStyle: MyTextStyles.textBlackBold14),
            ),

            // ///看状态
            // Container(
            //     alignment: Alignment.centerRight,
            //     padding: EdgeInsets.only(top: 5.w),
            //     child: const MyText("交易关闭", color: MyColours.colorFF4414, fontSize: 12)),
          ],
        ));
  }

  //订单详情
  _buildOrderDetail() {
    OrderModel orderModel = viewModel.orderModel;

    List<Map<String, String>> detailMap = [
      {"技师姓名:": orderModel.tName ?? ""},
      {"联系人:": orderModel.contacts ?? ""},
      {"联系电话:": orderModel.mMobile ?? ""},
      {"服务时间:": orderModel.orderServiceTime ?? ""},
      {"订单号:": orderModel.orderNo ?? ""},
      {"下单时间:": orderModel.createTime ?? ""},
    ];

    return Container(
        alignment: Alignment.centerLeft,
        decoration: BoxDecoration(
          color: MyColours.materialBg,
          //设置四周圆角 角度
          borderRadius: BorderRadius.circular(17.w),
        ),
        margin: EdgeInsets.only(top: 10.w, bottom: 10.w, left: 10.w, right: 10.w),
        padding: EdgeInsets.only(top: 10.w, bottom: 10.w, left: 10.w, right: 10.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
                padding: EdgeInsets.only(top: 5.w, bottom: 6.w),
                child: const MyText("订单详情", color: MyColours.text, fontSize: 14, fontWeight: FontWeight.bold)),
            // Column(
            //     crossAxisAlignment: CrossAxisAlignment.start,
            //     children: detailMap.map((e) {
            //       return Container(
            //           padding: EdgeInsets.symmetric(vertical: 6.w),
            //           child: MyText("${e.keys.first}${e.values.first}", color: MyColours.color676767, fontSize: 13));
            //     }).toList()),

            Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: detailMap.map((e) {
                  return Container(
                      padding: EdgeInsets.symmetric(vertical: 3.w),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          MyText(e.keys.first, color: MyColours.color676767, fontSize: 13.sp),
                          MyText(e.values.first, color: MyColours.text, fontSize: 13.sp),
                        ],
                      ));
                }).toList()),
          ],
        ));
  }

  //操作区域
  _buildOperationArea() {
    OrderModel orderModel = viewModel.orderModel;

    return SafeArea(
      child: Container(
          alignment: Alignment.centerRight,
          decoration: const BoxDecoration(color: MyColours.materialBg, boxShadow: <BoxShadow>[
            BoxShadow(
              color: Color.fromRGBO(0, 0, 0, 0.05),
              offset: Offset(0.0, -13),
              blurRadius: 12.0,
              spreadRadius: -9.0,
            )
          ]),
          padding: EdgeInsets.only(top: 12.5.h, right: 15.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              //金额
              Container(
                padding: EdgeInsets.only(left: 15.w),
                child: Row(
                  children: [
                    MyText("合计：", color: MyColours.text, fontSize: 13.sp, fontWeight: FontWeight.w600),
                    MyText("${orderModel.orderPrice}",
                        color: MyColours.colorE33432, fontSize: 17.sp, fontWeight: FontWeight.w600),
                  ],
                ),
              ),
              const Spacer(),
              MyTapWidget(
                  onTap: () {
                    if (orderModel.orderStatus == 1) {
                      //立即支付
                      OrderManager.payOrder(context, orderModel.orderId.toString(), orderModel.orderPrice ?? "");
                    } else {
                      //项目详情
                      NavigatorUtils.pushParams(
                          context, '${PackageDetailPage.routeName}?tId=${orderModel.tId}&gId=${orderModel.goodsId}');
                    }
                  },
                  child: MyBorder(
                    backgroundColor: MyColours.appMain,
                    color: MyColours.appMain,
                    radius: 20.h,
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 30.w, vertical: 10.w),
                      child: Text(
                        orderModel.orderStatus == 1 ? "立即付款" : "重新下单",
                        style: TextStyle(color: MyColours.materialBg, fontSize: 14.sp, fontWeight: FontWeight.w700),
                      ),
                    ),
                  )),
            ],
          )),
    );
  }

  @override
  Widget build(BuildContext context) {
    return BasePage<OrderDetailViewModel>(
      onModelReady: (model) async {
        // 页面初始化完成后的回调
        viewModel = model;
        viewModel.requestData();
      },
      viewModel: OrderDetailViewModel(widget.orderId),
      builder: (BuildContext context, OrderDetailViewModel model, Widget? child) {
        // cancelAccountViewModel = model;
        return Scaffold(
          backgroundColor: MyColours.materialBg,
          appBar: MyAppBar(
            title: model.orderModel.orderStatus == 1 ? "立即支付" : '订单详情',
            rightWidget: MyTapWidget(
                child: const MyText("取消订单"),
                onTap: () {
                  //取消订单
                  OrderManager.cancelOrder(
                      context, model.orderModel.orderId.toString(), model.orderModel.memberId.toString(),
                      onSure: (isSuccess) {
                    //刷新当前页面
                  });
                }),
          ),
          body: _buildBody(),
        );
      },
    );
  }
}
